//
//  KKAdviceExpertChatVC.m
//  DoMi
//
//  Created by 康凯 on 2016/12/10.
//  Copyright © 2016年 kk. All rights reserved.
//

#import "KKAdviceExpertChatVC.h"
#import "KKAudioRecorder.h"
#import "KKUploadUtils.h"
#import "KKVoiceView.h"
#import "KKChatCell.h"
#import "KKComHttp.h"
#import "KKAdviceDetailM.h"

@interface KKAdviceExpertChatVC ()<UITableViewDelegate,UITableViewDataSource,KKRecorderEventDelegate>
@property (weak, nonatomic) IBOutlet UILabel *expertName;
@property (weak, nonatomic) IBOutlet UILabel *company;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *inputView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *inputBottom;

@property (strong,nonatomic)KKVoiceView *recorderView;
@property(nonatomic,strong)KKAudioRecorder *recorder;
@property (strong, nonatomic) KKUploadUtils *uploadUtils;
@property (copy,nonatomic)NSString *questionContent;
@property (strong,nonatomic)NSTimer *timer;
@property (strong,nonatomic)KKAdviceDetailM *chatInfo;
@property (strong,nonatomic)NSArray *chatDatas;
@property (weak, nonatomic) IBOutlet UIView *backView;
@property (copy,nonatomic)NSString *recorderTime;
@end

@implementation KKAdviceExpertChatVC

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=YES;
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden=NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavWhite];
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    [self.tableView registerClass:[KKChatCell class] forCellReuseIdentifier:@"KKChatCell"];

    __weak typeof(self) weakSelf=self;
    self.recorder=[[KKAudioRecorder alloc]init];
    self.recorder.recorderSuccessBlock=^(NSURL *url){
        //创建文件管理器
        /*NSFileManager可以用来查询单词库目录，创建，重命名，删除目录以及获取／设置文件属性的方法*/
        NSFileManager * fm;
        fm = [NSFileManager defaultManager];
        //创建缓冲区，利用NSFileManager对象来获取文件中的内容，也就是这个文件的属性可修改
        NSData * fileData;
        fileData = [fm contentsAtPath:url.path];
        
        [weakSelf.uploadUtils uploadRecorderAudio:fileData];
    };
    
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(back)];
    [self.backView addGestureRecognizer:tap];
    //录制语音界面
    KKVoiceView *voice=[[[NSBundle mainBundle] loadNibNamed:@"KKVoiceView" owner:self options:nil] lastObject];
    self.recorderView=voice;
    self.recorderView.delegate=self;
    [self.view addSubview:self.recorderView];
    //上传语音
    self.uploadUtils=[[KKUploadUtils alloc] init];
    self.uploadUtils.uploadBlock=^(NSString *url){
        KKLog(@"url---->%@",url);
        weakSelf.questionContent=url;
        [weakSelf expertToAnswer];
    };
    [self getAdviceChatList];
}

#pragma mark tableview代理
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.chatDatas.count+1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KKChatCell *cell=[tableView dequeueReusableCellWithIdentifier:@"KKChatCell"];
    cell.flag=1;
    if(indexPath.row>0){
        [cell refreshCell:self.chatDatas[indexPath.row-1] index:indexPath.row];
    }else{
        cell.adviceFirst=self.chatInfo;
        [cell refreshCell:self.chatDatas[indexPath.row] index:indexPath.row];
    }
    
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row==0){
        if([self.chatInfo.asktype isEqualToString:@"1"]){
            return 50+45;
        }else{
            CGRect rec =  [self.chatInfo.question boundingRectWithSize:CGSizeMake(200, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:17]} context:nil];
            return rec.size.height + 45;
        }
    }else{
        KKChatM *model = self.chatDatas[indexPath.row-1];
        if([model.contenttype isEqualToString:@"1"]){
            return 50+45;
        }else{
            CGRect rec =  [model.content boundingRectWithSize:CGSizeMake(200, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:17]} context:nil];
            return rec.size.height + 45;
        }
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row==0){
        if([self.chatInfo.asktype isEqualToString:@"1"]){
            [self.recorder playAudio:self.chatInfo.question];
        }
    }else{
        KKChatM *model = self.chatDatas[indexPath.row-1];
        if([model.contenttype isEqualToString:@"1"]){
            [self.recorder playAudio:model.content];
        }
    }
}

#pragma mark voice代理
-(void)recorderTouchUp{
    [self.recorder openRecorder];
    self.timer=[NSTimer scheduledTimerWithTimeInterval:0.1 repeats:YES block:^(NSTimer * _Nonnull timer) {
        self.recorderView.time+=0.1;
        [self.recorderView setTime];
        self.recorderView.shapeLayer.strokeEnd+=0.001;
    }];
}
-(void)recorderTouchInside{
    if(self.recorderView.time>1.5){
        NSString *time=[NSString stringWithFormat:@"%.2f",self.recorderView.time];
        KKLog(@"time---->%@",time);
        NSArray *array= [time componentsSeparatedByString:@"."];
        int miao=[array[0] intValue];
        int fen=miao/60;
        self.recorderTime=[NSString stringWithFormat:@"0%d:%d0",fen,miao];
        self.recorderView.time=0.0;
        self.recorderView.shapeLayer.strokeEnd=0;
        [self.recorder stopRecorder:NO];
        [self.timer invalidate];
    }else{
        self.recorderView.time=0.0;
        [KKAppUtils toast:@"时间过短"];
        self.recorderView.shapeLayer.strokeEnd=0;
        [self.timer invalidate];
        [self.recorder stopRecorder:YES];
    }
}
-(void)recorderTouchMove{
    self.recorderView.time=0.0;
    [KKAppUtils toast:@"录制取消成功"];
    self.recorderView.shapeLayer.strokeEnd=0;
    [self.timer invalidate];
    [self.recorder stopRecorder:YES];
}

#pragma mark 接口--专家回答
-(void)expertToAnswer{
    NSDictionary *params=@{UID_KEY:UID,TOKEN_KEY:TOKEN,@"content":self.questionContent,@"consultid":self.consultId,@"times":self.recorderTime};
    [KKComHttp expertAnswer:params success:^(id data) {
        [self getAdviceChatList];
    } failure:^(NSError *error) {
        
    }];
}
#pragma mark 接口--咨询列表
-(void)getAdviceChatList{
    [self showDialog];
    [KKComHttp getAdviceDetail:self.consultId success:^(id data) {
        NSArray *chat=data;
        if(chat.count>0){
            self.chatInfo=chat[0];
            if([KKAppUtils isEmptyString:self.chatInfo.realname]){
                self.expertName.text=@"匿名";
            }else{
                self.expertName.text=self.chatInfo.realname;
            }
            self.company.text=@"专家";
            if(self.chatInfo.users!=nil&&self.chatInfo.users.count>0){
                self.chatDatas=self.chatInfo.users;
            }
        }
        [self.tableView reloadData];
        if(self.chatDatas.count>0){
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.chatDatas.count inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        }
        [self dismissDialog];
    } failure:^(NSError *error) {
        [self dismissDialog];
    }];
}

#pragma mark 按钮--返回
-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
//#pragma mark 按钮--发语音
//- (IBAction)recorderClick:(id)sender {
//    for (UIView *subView in self.view.subviews) {
//        if([subView isKindOfClass:[KKVoiceView class]]){
//            [subView removeFromSuperview];
//            self.inputBottom.constant=0;
//        }else{
//            [self.view addSubview:self.recorderView];
//            self.inputBottom.constant=241;
//        }
//    }
//}

@end
